# -*- coding: utf-8 -*-
# @Time    : 2022/9/14 16:11
# @Author  : Yanfeng
# @Email   : sxyanfeng2014@163.com
# @File    : baserequest.py
# @Software: PyCharm
import json
import re

import jsonpath
import requests
from requests.auth import HTTPBasicAuth

from  utils.times_tool.time_control import *

def regular(target) -> dict:
    target = json.dumps(target)
    EXPR = r'\$\{(.*?)\}'
    funcs = re.findall(EXPR,target)
    for func in funcs:
        value = eval(func)
        target = target.replace(r'${' + func + r'}', str(value))
    return json.loads(target)


def json_regular(target, erp):
    target = json.dumps(target)
    return jsonpath.jsonpath(target, erp)


class Base_request():
    session = requests.session()

    def post(self, url, headers, json1):
        json1 = regular(json)
        res = self.session.post(url=url, headers=headers, json=json1, verify=False)
        return res.json()

    def post_json(self, url, headers, json1):
        res = self.session.post(url=url, headers=headers, json=json1, verify=False)
        return res.json()

    def post_data(self, url, headers, data):
        res = self.session.post(url=url, headers=headers, data=data)
        return res.json()

    def post_data_text(self, url, headers, data):
        res = self.session.post(url=url, headers=headers, data=data)
        return res.text

    def get_data(self, url, data):
        res = self.session.get(url=url, params=data)
        return res.json()

    def post_basic_auth(self, text):
        """主动上报服务告警接口"""
        data1 = {
            "projectid": "erp",
            "svcname": "服务名称",
            "title": "主子库库存监控",
            "level": 1,
            "ops_person": "yanfeng",
            "mobiles": "18118758151",
            "content": text
        }
        res = self.session.post(url="http://dingtalk-robot.zhcxkj.com/abert", json=data1,
                                auth=HTTPBasicAuth("zhcxkj", "Zhcxkj#2022?ops"))
        return res.json()

    def post_auth(self, url, data, user, pwd):
        auth = HTTPBasicAuth(user, pwd)
        res = self.session.post(url=url, json=data, auth=auth)

        return res.json()
